{% extends 'base.html' %}
{% load static %}

{% block title %}代码执行器 - 对战平台{% endblock %}

{% block extra_css %}
<style>
    body {
        background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
        min-height: 100vh;
        color: rgba(255, 255, 255, 0.9);
    }

    .executor-card {
        background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
        backdrop-filter: blur(10px);
        border: 1px solid rgba(100, 150, 255, 0.3);
        border-radius: 20px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        margin-bottom: 20px;
    }

    .executor-header {
        background: linear-gradient(135deg, rgba(100, 150, 255, 0.2), rgba(0, 212, 255, 0.2));
        border-radius: 20px 20px 0 0;
        padding: 20px;
        border-bottom: 1px solid rgba(100, 150, 255, 0.3);
    }

    .code-editor {
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        font-size: 14px;
        line-height: 1.6;
        border: 1px solid rgba(100, 150, 255, 0.3);
        border-radius: 10px;
        padding: 15px;
        background: rgba(0, 0, 0, 0.7);
        color: #e8e8e8;
        min-height: 350px;
        resize: vertical;
        transition: all 0.3s ease;
    }

    .code-editor:focus {
        border-color: rgba(100, 150, 255, 0.6);
        box-shadow: 0 0 15px rgba(100, 150, 255, 0.3);
        outline: none;
    }

    .output-area {
        background: rgba(0, 0, 0, 0.9);
        color: #00ff88;
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        font-size: 13px;
        padding: 20px;
        border-radius: 10px;
        min-height: 250px;
        white-space: pre-wrap;
        word-wrap: break-word;
        overflow-y: auto;
        max-height: 450px;
        border: 1px solid rgba(100, 150, 255, 0.3);
        box-shadow: inset 0 2px 10px rgba(0, 0, 0, 0.5);
    }

    .error-output {
        color: #ff6b6b;
    }

    .success-output {
        color: #51cf66;
    }

    .execution-info {
        color: #74c0fc;
        font-size: 12px;
        margin-top: 10px;
        padding: 8px 12px;
        background: rgba(116, 192, 252, 0.1);
        border-radius: 5px;
        border-left: 3px solid #74c0fc;
    }

    .form-select,
    .form-control {
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(100, 150, 255, 0.3);
        border-radius: 10px;
        color: rgba(255, 255, 255, 0.9);
        padding: 12px 15px;
    }

    .form-select:focus,
    .form-control:focus {
        background: rgba(255, 255, 255, 0.15);
        border-color: rgba(100, 150, 255, 0.6);
        box-shadow: 0 0 15px rgba(100, 150, 255, 0.3);
        color: white;
    }

    .btn-execute {
        background: linear-gradient(135deg, #28a745, #20c997);
        border: none;
        color: white;
        padding: 12px 30px;
        border-radius: 25px;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
    }

    .btn-execute:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(40, 167, 69, 0.4);
        background: linear-gradient(135deg, #218838, #1e7e34);
    }

    .btn-clear {
        background: linear-gradient(135deg, #6c757d, #495057);
        border: none;
        color: white;
        padding: 12px 30px;
        border-radius: 25px;
        font-weight: 600;
        transition: all 0.3s ease;
        box-shadow: 0 4px 15px rgba(108, 117, 125, 0.3);
    }

    .btn-clear:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(108, 117, 125, 0.4);
        background: linear-gradient(135deg, #5a6268, #343a40);
    }

    .loading-spinner {
        display: none;
    }

    .loading .loading-spinner {
        display: inline-block;
    }

    .template-btn {
        background: rgba(100, 150, 255, 0.2);
        border: 1px solid rgba(100, 150, 255, 0.3);
        color: rgba(255, 255, 255, 0.9);
        padding: 8px 16px;
        border-radius: 15px;
        font-size: 0.9rem;
        transition: all 0.3s ease;
    }

    .template-btn:hover {
        background: rgba(100, 150, 255, 0.3);
        border-color: rgba(100, 150, 255, 0.5);
        color: white;
        transform: translateY(-1px);
    }
</style>
{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="executor-card">
        <div class="executor-header">
            <h2 class="mb-2">
                <i class="fas fa-code me-3"></i>
                代码执行器
            </h2>
            <p class="mb-0 opacity-75">在服务器上运行代码并查看执行结果，支持多种编程语言</p>
        </div>
    </div>

    <div class="row">
        <div class="col-md-8">
            <div class="executor-card">
                <div class="card-body p-4">
                    <!-- 语言选择 -->
                    <div class="mb-4">
                        <label for="language" class="form-label fw-bold">
                            <i class="fas fa-language me-2"></i>
                            选择编程语言:
                        </label>
                        <select class="form-select" id="language">
                            {% for lang_key, lang_info in supported_languages.items %}
                            <option value="{{ lang_key }}" {% if lang_key=='python' %}selected{% endif %}>
                                {{ lang_info.name }} ({{ lang_info.extension }})
                            </option>
                            {% endfor %}
                        </select>
                    </div>

                    <!-- 代码模板选择 -->
                    <div class="code-templates">
                        <label for="code-template" class="form-label">选择代码模板:</label>
                        <select class="form-select" id="code-template">
                            <option value="">-- 选择模板或从已有代码加载 --</option>
                            {% for code in user_codes %}
                            <option value="{{ code.id }}" data-language="{{ code.language }}">
                                {{ code.title }} ({{ code.language }})
                            </option>
                            {% endfor %}
                        </select>
                    </div>

                    <!-- 代码编辑器 -->
                    <div class="mb-3">
                        <label for="code" class="form-label">代码:</label>
                        <textarea class="form-control code-editor" id="code"
                            placeholder="在这里输入你的代码...">print("Hello, World!")</textarea>
                    </div>

                    <!-- 输入数据 -->
                    <div class="mb-3">
                        <label for="input-data" class="form-label">输入数据 (可选):</label>
                        <textarea class="form-control" id="input-data" rows="3"
                            placeholder="程序运行时的输入数据，每行一个输入..."></textarea>
                    </div>

                    <!-- 执行按钮 -->
                    <div class="mb-3">
                        <button type="button" class="btn btn-execute" id="execute-btn">
                            <span class="loading-spinner spinner-border spinner-border-sm me-2" role="status"></span>
                            <i class="fas fa-play"></i> 执行代码
                        </button>
                        <button type="button" class="btn btn-clear" id="clear-btn">
                            <i class="fas fa-trash"></i> 清空输出
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <!-- 支持的语言信息 -->
            <div class="executor-card mb-3">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-info-circle me-2"></i>支持的语言</h6>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled mb-0">
                        {% for lang_key, lang_info in supported_languages.items %}
                        <li class="mb-2">
                            <strong class="text-light">{{ lang_info.name }}</strong><br>
                            <small class="text-muted">{{ lang_info.extension }} 文件</small>
                        </li>
                        {% endfor %}
                    </ul>
                </div>
            </div>

            <!-- 使用说明 -->
            <div class="executor-card">
                <div class="card-header">
                    <h6 class="mb-0"><i class="fas fa-question-circle me-2"></i>使用说明</h6>
                </div>
                <div class="card-body">
                    <ul class="small mb-0 text-light">
                        <li class="mb-1">选择编程语言后输入代码</li>
                        <li class="mb-1">可以从已有代码中选择模板</li>
                        <li class="mb-1">如需输入数据，在输入框中填写</li>
                        <li class="mb-1">点击执行按钮运行代码</li>
                        <li class="mb-1">执行时间限制为10秒</li>
                        <li class="mb-1">输出结果会显示在下方</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <!-- 输出区域 -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="executor-card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-terminal me-2"></i>执行结果</h5>
                </div>
                <div class="card-body p-0">
                    <div class="output-area" id="output">
                        等待执行代码...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    $(document).ready(function () {
        // 语言模板
        const languageTemplates = {
            'python': 'print("Hello, World!")',
            'javascript': 'console.log("Hello, World!");',
            'java': 'public class Main {\n    public static void main(String[] args) {\n        System.out.println("Hello, World!");\n    }\n}',
            'cpp': '#include <iostream>\nusing namespace std;\n\nint main() {\n    cout << "Hello, World!" << endl;\n    return 0;\n}',
            'c': '#include <stdio.h>\n\nint main() {\n    printf("Hello, World!\\n");\n    return 0;\n}'
        };

        // 语言切换
        $('#language').change(function () {
            const language = $(this).val();
            if (languageTemplates[language]) {
                $('#code').val(languageTemplates[language]);
            }
        });

        // 代码模板选择
        $('#code-template').change(function () {
            const codeId = $(this).val();
            if (codeId) {
                // 这里可以通过AJAX加载具体的代码内容
                // 暂时使用选项的语言信息
                const selectedOption = $(this).find('option:selected');
                const language = selectedOption.data('language');
                if (language) {
                    $('#language').val(language);
                }
            }
        });

        // 执行代码
        $('#execute-btn').click(function () {
            const code = $('#code').val().trim();
            const language = $('#language').val();
            const inputData = $('#input-data').val();

            if (!code) {
                alert('请输入代码！');
                return;
            }

            // 显示加载状态
            $(this).addClass('loading').prop('disabled', true);
            $('#output').html('<span class="text-info">正在执行代码...</span>');

            // 发送执行请求
            $.ajax({
                url: '{% url "battles:api_code_execute" %}',
                method: 'POST',
                headers: {
                    'X-CSRFToken': $('[name=csrfmiddlewaretoken]').val()
                },
                data: JSON.stringify({
                    code: code,
                    language: language,
                    input: inputData
                }),
                contentType: 'application/json',
                success: function (response) {
                    if (response.success) {
                        let output = '';
                        if (response.output) {
                            output += '<span class="success-output">' + escapeHtml(response.output) + '</span>';
                        }
                        if (response.error) {
                            if (output) output += '\n\n';
                            output += '<span class="error-output">错误信息:\n' + escapeHtml(response.error) + '</span>';
                        }
                        output += '<div class="execution-info">执行时间: ' + response.execution_time.toFixed(3) + ' 秒</div>';
                        $('#output').html(output);
                    } else {
                        $('#output').html('<span class="error-output">执行失败: ' + escapeHtml(response.error) + '</span>');
                    }
                },
                error: function (xhr) {
                    let errorMsg = '请求失败';
                    if (xhr.responseJSON && xhr.responseJSON.error) {
                        errorMsg = xhr.responseJSON.error;
                    }
                    $('#output').html('<span class="error-output">错误: ' + escapeHtml(errorMsg) + '</span>');
                },
                complete: function () {
                    $('#execute-btn').removeClass('loading').prop('disabled', false);
                }
            });
        });

        // 清空输出
        $('#clear-btn').click(function () {
            $('#output').html('等待执行代码...');
        });

        // HTML转义函数
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
    });
</script>
{% endblock %}